<script setup>
import { onMounted, onUnmounted, computed, ref } from "vue";
import { useRouter } from "vue-router";
import { lStorage } from "@/utils/storage";

import useInstructionStore from "@/store/modules/instructionList.js";
import { useWarnPollingStore } from "@/store/modules/warnPolling.js";

const router = useRouter();
const cachedComponents = ref(new Set());

// 优化后的缓存键
const cacheKey = computed(() => router.currentRoute.value.name);

// 精准缓存控制
const updateCache = (to, from) => {
  if (from?.meta.keepAlive) {
    cachedComponents.value.add(from.name);
    console.log(`[缓存] 添加 ${from.name}`);
  }

  if (to?.meta.keepAlive) {
    cachedComponents.value.add(to.name);
    console.log(`[缓存] 保留 ${to.name}`);
  } else {
    cachedComponents.value.delete(to.name);
    console.log(`[缓存] 移除 ${to.name}`);
  }

  // 限制缓存数量
  if (cachedComponents.value.size > 10) {
    const oldest = [...cachedComponents.value][0];
    cachedComponents.value.delete(oldest);
    console.log(`[缓存] 淘汰 ${oldest}`);
  }
};

onMounted(async () => {
  router.afterEach(updateCache);

  if (lStorage.get("USER_TOKEN")) {
    await useInstructionStore().getData();
    if (!useWarnPollingStore().pollTimer) {
      await useWarnPollingStore().startPolling();
    }
  }
});

onUnmounted(() => {
  cachedComponents.value.clear();
  useWarnPollingStore().stopPolling();
});
</script>

<template>
  <router-view v-slot="{ Component }">
    <keep-alive :include="Array.from(cachedComponents)" :max="10">
      <component :is="Component" :key="cacheKey" class="router-component" />
    </keep-alive>
  </router-view>
</template>
